import {Injectable} from '@angular/core';
import {
    ActivatedRouteSnapshot,
    CanActivate,
    CanActivateChild,
    Router,
    RouterStateSnapshot,
} from '@angular/router';
import {StorageKey} from '../storage.key';
import {StorageService} from './storage.service';

@Injectable({
    providedIn: 'root',
})
export class LoginGuardService implements CanActivate, CanActivateChild {

    constructor(private storageService: StorageService, private router: Router) {
    }

    async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
        return await this.checkLogin();
    }

    async canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
       console.log(childRoute, state);
        return await this.checkLogin();
    }

    async checkLogin() {
        const token = await this.storageService.get(StorageKey.TOKEN);
        console.log(token);
        if (token) {
            return true;
        } else {
            await this.router.navigateByUrl('/auth/login');
            return false;
        }
    }
}
